//
//  AddDescribeViewController.m
//  Mahjong
//
//  Created by mc on 16/9/9.
//  Copyright © 2016年 Elliot. All rights reserved.
//

#import "AddDescribeViewController.h"
#import "AddDescribeTableViewCell.h"
#import "ZYQAssetPickerController.h"

#define WIDTH ([UIScreen mainScreen].bounds.size.width)
#define HEIGHT ([UIScreen mainScreen].bounds.size.height)
@interface AddDescribeViewController ()<ZYQAssetPickerControllerDelegate,UITableViewDelegate,UITableViewDataSource>
{
    NSArray *CellArray;
    NSString *addressString;
    UIView               *_editv;
    UILabel              *starLabel;
//    HCSStarRatingView    *starRatingView;
    UIButton             *_addPic;
    NSMutableArray       *_imageArray;
}

@property (nonatomic, strong) UIView *backView;
@property (nonatomic, strong) UIView *textBackView;
@property (nonatomic, strong) UITableView *textDescribeTableView;
@property (nonatomic, strong) UILabel *describeText;
@end

@implementation AddDescribeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.view.backgroundColor = [UIColor colorWithWhite:0.900 alpha:1.000];
    
    CellArray = [[NSArray alloc] initWithObjects:@"转盘坏了, 麻将机不能洗牌",@"我的麻将机卡住了, 摆不了拍牌",@"弹簧报废, 需要换修",@"麻将机桌子腿瘸了, 需要换修", nil];

//    [self addNav];
    [self addRepairResultUI];
    [self addTextDescribeTableviewUI];
    
    self.navigationItem.title = @"维修";
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_but_back"] style:(UIBarButtonItemStyleDone) target:self action:@selector(backAction)];
    backItem.tintColor = [UIColor grayColor];
    self.navigationItem.leftBarButtonItem = backItem;
    
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)addNav{
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, WIDTH, 40)];
    _backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_backView];
    
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [backBtn setImage:[UIImage imageNamed:@"nav_but_back"] forState:UIControlStateNormal];
    backBtn.backgroundColor = [UIColor clearColor];
    backBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [backBtn addTarget:self action:@selector(backBtnAction) forControlEvents:UIControlEventTouchUpInside];
    backBtn.frame = CGRectMake(20, 5, 25, 25);
    [_backView addSubview:backBtn];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(WIDTH / 4, 0, WIDTH / 2, 40)];
    lable.backgroundColor = [UIColor whiteColor];
    lable.text = @"维修";
    lable.font = [UIFont systemFontOfSize:20];
    lable.textAlignment = NSTextAlignmentCenter;
    [self.backView addSubview:lable];
    
}
-(void)backBtnAction{
    [self.navigationController popViewControllerAnimated:YES];
}
// 维修发布
-(void)addRepairResultUI{
    UILabel *repairLable = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.backView.frame) + 10, WIDTH, HEIGHT / 20)];
    repairLable.backgroundColor = [UIColor whiteColor];
    repairLable.text = @"维修发布";
    repairLable.font = [UIFont systemFontOfSize:17];
    repairLable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:repairLable];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(repairLable.frame) +2 , WIDTH, HEIGHT / 20)];
    lable.backgroundColor = [UIColor whiteColor];
    lable.text = @"  添加需要维修物品的照片(最多六张)";
    lable.textColor = [UIColor colorWithWhite:0.500 alpha:1.000];
    lable.font = [UIFont systemFontOfSize:15];
    //    lable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:lable];
    
    UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(lable.frame)+2, WIDTH, HEIGHT / 4)];
    backView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:backView];
    
    // 评论 + 照片
    _editv = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(lable.frame)+2, WIDTH, HEIGHT / 4)];
    _editv.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_editv];
    
    
    // + pic
    _addPic = [UIButton buttonWithType:UIButtonTypeCustom];
    _addPic.frame = CGRectMake(10, 15, 70, 70);
    [_addPic setImage:[UIImage imageNamed:@"service_but_addpicture@2x"] forState:UIControlStateNormal];
    [_addPic addTarget:self action:@selector(imageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    _addPic.tag = 3000;
    [_editv addSubview:_addPic];
    
    UILabel *textLable = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(backView.frame) +2 , WIDTH, HEIGHT / 20)];
    textLable.backgroundColor = [UIColor whiteColor];
    textLable.text = @"  添加文字描述";
    textLable.textColor = [UIColor colorWithWhite:0.500 alpha:1.000];
    textLable.font = [UIFont systemFontOfSize:15];
    //    lable.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:textLable];
    UIButton *textLableBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    textLableBtn.frame = CGRectMake(WIDTH - HEIGHT / 20 - 10, CGRectGetMaxY(backView.frame) +2, 30, HEIGHT / 20);
    [textLableBtn addTarget:self action:@selector(imageBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    textLableBtn.backgroundColor = [UIColor whiteColor];
    [textLableBtn setImage:[UIImage imageNamed:@"service_but_write_close"] forState:UIControlStateNormal];
    textLableBtn.tag = 3001;
    [self.view addSubview:textLableBtn];
    
    self.textBackView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(textLableBtn.frame)+2, WIDTH, HEIGHT / 5)];
    _textBackView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_textBackView];
    self.describeText
    = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, WIDTH -20, HEIGHT / 25)];
//    describeText.backgroundColor = [UIColor redColor];
//    _describeText.text = @"我的麻将机卡住了,摆不了牌";
    _describeText.textColor = [UIColor colorWithWhite:0.500 alpha:1.000];
    _describeText.numberOfLines = 0;
    [_textBackView addSubview:_describeText];
    
}
-(void)imageBtnAction:(UIButton *)button{
    NSLog(@"%ld",(long)button.tag);
    if (3001 == button.tag) {
        AddDescribeViewController *addDescribeVC = [[AddDescribeViewController alloc] init];
        [self.navigationController pushViewController:addDescribeVC animated:YES];
    }else{
        if (_imageArray.count >= 6) {
            NSLog(@"最多只能上传9张图片");
        } else {
            [self selectPictures];
        }
        
    }

}
// 本地相册选择多张照片
- (void)selectPictures
{
    ZYQAssetPickerController *picker = [[ZYQAssetPickerController alloc] init];
    picker.maximumNumberOfSelection = 6-_imageArray.count;
    picker.assetsFilter = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups = NO;
    picker.delegate = self;
    picker.selectionFilter = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings)
                              {
                                  if ([[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyType] isEqual:ALAssetTypeVideo])
                                  {
                                      NSTimeInterval duration = [[(ALAsset *)evaluatedObject valueForProperty:ALAssetPropertyDuration] doubleValue];
                                      
                                      return duration >= 5;
                                  } else {
                                      return YES;
                                  }
                              }];
    
    [self presentViewController:picker animated:YES completion:NULL];
}
// 9宫格图片布局
- (void)nineGrid
{
    for (UIImageView *imgv in _editv.subviews)
    {
        if ([imgv isKindOfClass:[UIImageView class]]) {
            [imgv removeFromSuperview];
        }
    }
    
    CGFloat width = kUIScreenWidth/5;
    CGFloat widthSpace = (WIDTH - 15*4 - (kUIScreenWidth/5.5
                                          )*4) / 3.0;
    CGFloat heightSpace = 10;
    
    NSInteger count = _imageArray.count;
    _imageArray.count > 6 ? (count = 6) : (count = _imageArray.count);
    
    for (int i=0; i<count; i++)
    {
        UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(15+(width+widthSpace)*(i%4), (i/4)*(width+heightSpace) +15, width, width)];
        imgv.image = _imageArray[i];
        imgv.userInteractionEnabled = YES;
        [_editv addSubview:imgv];
        
        //        UIButton *delete = [UIButton buttonWithType:UIButtonTypeCustom];
        //        delete.frame = CGRectMake(width-16, 0, 16, 16);
        ////        delete.backgroundColor = [UIColor greenColor];
        //        [delete addTarget:self action:@selector(deleteEvent:) forControlEvents:UIControlEventTouchUpInside];
        //        delete.tag = 10+i;
        //        [delete setImage:[UIImage imageNamed:@"else_but_closepop@2x"] forState:UIControlStateNormal];
        //        [imgv addSubview:delete];
        
        if (i == _imageArray.count - 1)
        {
            if (_imageArray.count % 4 == 0) {
                _addPic.frame = CGRectMake(15, CGRectGetMaxY(imgv.frame) + heightSpace, 70, 70);
            } else {
                _addPic.frame = CGRectMake(CGRectGetMaxX(imgv.frame) + widthSpace, CGRectGetMinY(imgv.frame), 70, 70);
            }
            
            _editv.frame = CGRectMake(0, CGRectGetMaxY(self.backView.frame) +22 + HEIGHT/20 + [UIScreen mainScreen].bounds.size.width/4 + HEIGHT / 20 + HEIGHT/20 , WIDTH, CGRectGetMaxY(_addPic.frame)+20);
            starLabel.frame = CGRectMake(20, _editv.frame.size.height-105, WIDTH, 20);
//            starRatingView.frame = CGRectMake(20, _editv.frame.size.height-75, 200, 25);
        }
    }
}

// 删除照片
//- (void)deleteEvent:(UIButton *)sender
//{
//    UIButton *btn = (UIButton *)sender;
//    [_imageArray removeObjectAtIndex:btn.tag-10];
//
//    [self nineGrid];
//
//    if (_imageArray.count == 0)
//    {
//        _addPic.frame = CGRectMake(15, CGRectGetMaxY(_textView.frame)+15, 70, 70);
//        _editv.frame = CGRectMake(0, 95, ScreenWidth, CGRectGetMaxY(_addPic.frame)+20+50);
//    }
//}

#pragma mark - ZYQAssetPickerController Delegate

- (void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)assets
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
                   {
                       for (int i=0; i<assets.count; i++)
                       {
                           ALAsset *asset = assets[i];
                           UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
                           [_imageArray addObject:tempImg];
                           
                           dispatch_async(dispatch_get_main_queue(), ^{
                               [self nineGrid];
                           });
                       }
                   });
}


- (void)addTextDescribeTableviewUI {
    self.textDescribeTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_textBackView.frame)+ 5, WIDTH, HEIGHT/2) style:UITableViewStyleGrouped];
    self.textDescribeTableView.delegate = self;
    self.textDescribeTableView.dataSource = self;
    self.textDescribeTableView.backgroundColor = [UIColor whiteColor];
    [self.textDescribeTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
//    [self.textDescribeTableView setSeparatorColor:[UIColor redColor]];
//    self.textDescribeTableView.scrollEnabled = NO;
    //使用storyboard实现cell的自适应高度。。注意不要在实现返回cell高度的代理方法了。。。前提是使用xib创建了cell病已经使用了autolayout
    //    AccountSettableview.estimatedRowHeight = 100;
    //    AccountSettableview.rowHeight = UITableViewAutomaticDimension;
    //
    [self.view addSubview:self.textDescribeTableView];
}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return CellArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"AddDescribeTableviewCell";
    AddDescribeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[AddDescribeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.lableText.text = CellArray[indexPath.row];
    cell.lableText.textColor = [UIColor colorWithWhite:0.500 alpha:1.000];
    
    return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return (160*HEIGHT)/2204;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001;
}
#pragma mark -- UITableViewDatasource
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView reloadData];
    AddDescribeTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.lableText.textColor = [UIColor redColor];
    _describeText.text = CellArray[indexPath.row];
    
}

//-(void)viewWillAppear:(BOOL)animated{
//    [super viewWillAppear:animated];
//    self.navigationController.navigationBar.translucent = YES;
//    
//}
//-(void)viewWillDisappear:(BOOL)animated{
//    [super viewWillDisappear:animated];
//    self.navigationController.navigationBar.translucent = NO;
//    
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
